package org.dtrd.common.util;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {

    private final static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 得到格式化json数据 退格用\t 换行用\r
     */
    public static String formatJson(String jsonStr) {
        int level = 0;
        StringBuffer jsonForMatStr = new StringBuffer();
        for (int i = 0; i < jsonStr.length(); i++) {
            char c = jsonStr.charAt(i);
            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
                jsonForMatStr.append(getLevelStr(level));
            }
            switch (c) {
                case '{':
                case '[':
                    jsonForMatStr.append(c + "\n");
                    level++;
                    break;
                case ',':
                    jsonForMatStr.append(c + "\n");
                    break;
                case '}':
                case ']':
                    jsonForMatStr.append("\n");
                    level--;
                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
                    break;
            }
        }

        return jsonForMatStr.toString();

    }

    private static String getLevelStr(int level) {
        StringBuffer levelStr = new StringBuffer();
        for (int levelI = 0; levelI < level; levelI++) {
            levelStr.append("\t");
        }
        return levelStr.toString();
    }

    /**
     * 处理字符串
     *
     * @param oldStr
     * @return
     */
    public static String StrTrim(String oldStr) {
//		if (oldStr == null || oldStr.trim().toLowerCase().equals("null") || oldStr.trim().toLowerCase().indexOf("null") >= 0)
        if (oldStr == null || oldStr.trim().toLowerCase().equals("null"))
            return "";
        else
            return oldStr.trim();
    }

    public static String StrTrim(Object oject) {
        if (oject == null)
            return "";
        else
            return oject.toString().trim();
    }

    public static String StrTrimDate(Object oject) {
        if (oject == null)
            return "";
        else {
            if (oject.toString().length() > 10)
                return oject.toString().trim().substring(0, 10);

            else
                return oject.toString().trim();

        }
    }

    public static String StrTrimLong(long number) {
        if (number == 0)
            return "";
        else {
            return String.valueOf(number);
        }
    }

    public static long StrTrimLong(Object number) {
        if (number == null)
            return 0;
        String num = String.valueOf(number);
        if (num.equals("") || num.equals("null"))
            return 0l;
        try {
            return Long.valueOf(num);
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        return 0l;
    }

    public static int StrTrimInt(Object oject) {
        int result = 0;
        if (oject == null) {
            return 0;
        }
        String number = String.valueOf(oject).trim();
        if (number.equals("") || number.equals("null"))
            return 0;
        try {
            result = new Double(number).intValue();
            return result;
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        return 0;
    }

    public static BigDecimal StrTrimBigDecimal(Object oject) {
        BigDecimal result = new BigDecimal(0);
        if (oject == null)
            return result;
        String number = String.valueOf(oject).trim();
        if (number.equals("") || number.equals("null"))
            return result;
        try {
            result = new BigDecimal(number);
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        return result;
    }

    public static float StrTrimFloat(Object number) {
        return StrTrimFloat(String.valueOf(number));
    }

    public static float StrTrimFloat(String number) {
        float result = 0f;
        if (number == null || "".equals(number) || number.equals("null"))
            return 0.00f;
        try {
            result = Float.parseFloat(number);
            return result;
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        return result;
    }

    public static float trimFloat(Float number) {
        return number == null ? 0f : number.floatValue();
    }

    public static String StrTrimTime(Object oject) {
        if (oject == null)
            return "";
        else {
            if (oject.toString().length() > 19)
                return oject.toString().trim().substring(0, 19);
            else
                return oject.toString().trim();

        }
    }

    public static String StrTrimTimeWithoutDate(Object oject) {
        if (oject == null)
            return "";
        else {
            if (oject.toString().length() >= 16)
                return oject.toString().trim().substring(11, 16);
            else
                return oject.toString().trim();

        }
    }

    public static String StrTrimAndTransFromGBToISO(String oldStr) {
        try {
            if (oldStr == null || oldStr.trim().toLowerCase().equals("null"))
                return "";
            else
                return new String(oldStr.trim().getBytes("gb2312"), "ISO8859_1");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public static String StrTrimAndTransFromISOToGB(Object oject) {
        try {
            if (oject == null)
                return "";
            else
                return new String(oject.toString().getBytes("ISO8859_1"), "gb2312");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public static String StrTrimAndTransFromGBToISO(Object oject) {
        try {
            if (oject == null)
                return "";
            else
                return new String(oject.toString().getBytes("gb2312"), "ISO8859_1");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public static String StrTrimAndTransFromGBToUTF8(Object oject) {
        try {
            if (oject == null)
                return "";
            else
                return new String(oject.toString().getBytes("gb2312"), "utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * MD5-Hex加密
     *
     * @param origin
     * @return
     */
    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(origin.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    /**
     * 转换字节数组为16进制字串
     * <p>
     * 字节数组
     *
     * @return 16进制字串
     */
    public static String byteArrayToHexString(byte bytes[]) {
        // int pos = 0;
        // char[] c = new char[b.length * 2];
        // for (int i = 0; i < b.length; i++) {
        // c[pos++] = hexDigits[(b[i] >> 4) & 0x0F];
        // c[pos++] = hexDigits[b[i] & 0x0f];
        // }
        // return new String(c);

        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();

    }

    /**
     * 转换16进制ASCII字符串为普通字符串
     *
     * @param input 16进制ASCII字符串
     * @return 普通字符串
     */
    public static String formatASCII(String input) {
        String output = "";
        StringBuffer sb = new StringBuffer();
        byte[] bArr = input.getBytes();
        for (int i = 0; i < bArr.length; i++) {
            if (i % 2 == 0) {
                sb.append('%');
            }
            sb.append((char) bArr[i]);
        }
        try {
            output = URLDecoder.decode(sb.toString(), "GBK");
        } catch (Exception e) {
            return "";
        }
        return output;
    }

    /**
     * 判断字符串是否是数字
     */
    public static boolean isValidNumber(String str) {
        if (str == null)
            return false;
        if (str.endsWith(".0"))
            str = str.substring(0, str.length() - 2);
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 中文编码转换
     *
     * @param str String
     * @return String
     */
    public static String toGBK(String str) {
        if (str != null) {
            try {
                str = new String(str.getBytes("ISO-8859-1"), "gb2312");// ！！！
            } catch (Exception e) {
                System.out.println("toGBK Exception:" + e.getMessage());
                System.out.println("The String is:" + str);
            }
        }
        return str;
    }

    /**
     * 中文编码转换
     *
     * @param str 原始字符串 charsetName 字符集名称，如"ISO" String
     * @return String
     */
    public static String toGBK(String str, String charsetName) {
        if (str != null && charsetName != null) {
            try {
                str = new String(str.getBytes(charsetName), "gb2312");// ！！！
            } catch (Exception e) {
                System.out.println("toGBK Exception:" + e.getMessage());
                System.out.println("The String is:" + str);
            }
        }
        return str;
    }

    public static void testStringCharset(String str) {
        try {
            System.out.println("[ISO8859-1]:  " + new String(str.getBytes("ISO8859-1"), "gb2312"));
            System.out.println("[ISO-8859-1]:  " + new String(str.getBytes("ISO-8859-1"), "gb2312"));
            System.out.println("[UTF8]:  " + new String(str.getBytes("UTF8"), "gb2312"));
            System.out.println("[UTF-8]:  " + new String(str.getBytes("UTF-8"), "gb2312"));
            System.out.println("[GB2312]:  " + new String(str.getBytes("GB2312"), "gb2312"));
            System.out.println("[GBK]:  " + new String(str.getBytes("GBK"), "gb2312"));
            System.out.println("[BIG5]:  " + new String(str.getBytes("BIG5"), "gb2312"));
            System.out.println("[UNICODE]:  " + new String(str.getBytes("UNICODE"), "gb2312"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String cutString(String str, int length) {
        if ((length > 0) && (str.length() > length)) {
            return str.substring(0, length) + ".";
        } else
            return str;
    }

    // 获得文件后缀名:
    public static String getFileType(String fileName) {
        String result = "file";
        if (fileName.contains(".")) {
            result = fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return result;
    }

    /**
     * 将普通文本格式字符串装换为html字符串
     *
     * @param in
     * @return
     */
    public static String toHTMLString(String in) {
        StringBuffer out = new StringBuffer();
        for (int i = 0; in != null && i < in.length(); i++) {
            char c = in.charAt(i);
            if (c == '\'')
                out.append("&#039;");
            else if (c == '\"')
                out.append("&#034;");
            else if (c == '<')
                out.append("&lt;");
            else if (c == '>')
                out.append("&gt;");
            else if (c == '&')
                out.append("&amp;");
            else if (c == ' ')
                out.append("&nbsp;");
            else if (c == '\n')
                out.append("<br/>");
            else
                out.append(c);
        }
        return out.toString();
    }

    /**
     * 去除html字符串的格式
     *
     * @param htmlstr
     * @return
     */
    public static String toTxtString(String htmlstr) {
        String result = StrTrim(htmlstr);
        // 去除html格式
        result = result.replaceAll("<([^<>]+)>", "").replace("&nbsp;", "");
        return result;
    }

    // 转为unicode
    public static void writeUnicode(final DataOutputStream out, final String value) {
        try {
            final String unicode = codeUnicode(value);
            final byte[] data = unicode.getBytes();
            final int dataLength = data.length;

            System.out.println("Data Length is: " + dataLength);
            System.out.println("Data is: " + value);
            out.writeInt(dataLength); // 先写出字符串的长度
            out.write(data, 0, dataLength); // 然后写出转化后的字符串
        } catch (IOException e) {

        }
    }

    /**
     * 将普通字符串转为unicode编码，如输入【测试】，返回【&#x6d4b;&#x8bd5;】
     *
     * @param dataStr
     * @return 转换后的字符串
     */
    public static String codeUnicode(final String dataStr) {
        char[] utfBytes = dataStr.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "&#x" + hexB + ";";
        }
        return unicodeBytes;
    }

    /**
     * 用于测试codeUnicode函数
     *
     * @param gbString
     */
    private static void gbEncoding(final String gbString) {
        System.out.println(gbString + "unicodeBytes is: ");
        System.out.println(codeUnicode(gbString));
    }

    /**
     * 转换字符串为int型值
     *
     * @param str      待转换的字符串
     * @param defvalue 转换失败时的默认返回值
     * @return
     */
    public static int parseStrToInt(String str, int defvalue) {
        try {
            int result = new Integer(str).intValue();
            return result;
        } catch (Exception e) {
            return defvalue;
        }
    }

    public static double toDouble(String floatstr) {
        if (floatstr == null || floatstr.equals(""))
            return 0d;
        return Double.parseDouble(floatstr);
    }

    public static Double parseStrToDouble(String str, double defvalue) {
        try {
            System.out.println(str);
            Double result = new Double(str);
            return result;
        } catch (Exception e) {
            System.out.println(defvalue);
            return new Double(defvalue);
        }
    }

    /**
     * 功能介绍:将unicode字符串转为汉字，如输入【&#x6d4b;&#x8bd5;】，返回【测试】
     *
     * @param dataStr 源unicode字符串
     * @return 转换后的字符串
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("&#x", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 3, dataStr.length() - 1);
            } else {
                charStr = dataStr.substring(start + 3, end - 1);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    public static final String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static void printCode(String[] strArr, String codeTmpl) {
        if (strArr != null && strArr.length > 0 && codeTmpl != null) {
            for (int i = 0; i < strArr.length; i++) {
                System.out.println(codeTmpl.replaceAll("@var", strArr[i]));
            }
        }
    }

    /**
     * 取得32位随机永不重复UUID
     *
     * @return
     */

    /*
     * public static String getRandomUUID() { return new
     * String(Hex.encodeHex(org.apache.commons.id.uuid.UUID
     * .randomUUID().getRawBytes())); }
     */

    /**
     * 取得字符串中的数字，按顺序组合成字符串
     *
     * @return
     */
    public static String getNumberStr(String s) {
        String result = "";
        s = s.trim();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
                result = result + s.charAt(i);
        }
        return result;
    }

    private static SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");

    public static String concatYear(String name) {
        String createdate = name;
        if (name.startsWith("2010") || name.startsWith("2011") || name.startsWith("2012")) {
            // 真到2012年了，恐怕这程序早被改了

        } else {
            createdate = sd.format(new Date()).substring(0, 4) + "." + name;
        }
        createdate = createdate.replace(".", "-");
        return createdate;
    }

    /**
     * 将传入的秒数按照指定格式转化为字符串，如传入100,"hh:mi:ss",返回"00:01:40"
     *
     * @param second 秒数
     * @param format 指定格式，如“hh:mi:ss”，“mi:ss”
     * @return
     */
    public static String getFormatTimeBySecond(int second, String format) {
        int hour;
        int minute;
        int thissecond;
        String strhour = "";
        String strminute = "";
        String strsecond = "";
        if (format.equals("hh:mi:ss")) {
            hour = second / 3600;
            strhour = "" + hour;
            if (hour < 10)
                strhour = "0" + hour;
            minute = second / 60;
            strminute = "" + minute;
            if (minute < 10)
                strminute = "0" + minute;
            thissecond = second % 60;
            strsecond = "" + thissecond;
            if (thissecond < 10)
                strsecond = "0" + thissecond;

            return strhour + ":" + strminute + ":" + strsecond;
        } else if (format.equals("mi:ss")) {
            minute = second / 60;
            strminute = "" + minute;
            if (minute < 10)
                strminute = "0" + minute;
            thissecond = second % 60;
            strsecond = "" + thissecond;
            if (thissecond < 10)
                strsecond = "0" + thissecond;
            return strminute + ":" + strsecond;
        }
        return "";
    }

    /**
     * Utf8URL编码
     *
     * @return
     */
    public static String Utf8URLencode(String text) {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < text.length(); i++) {

            char c = text.charAt(i);
            if (c >= 0 && c <= 255) {
                result.append(c);
            } else {

                byte[] b = new byte[0];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception ex) {
                }

                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    result.append("%" + Integer.toHexString(k).toUpperCase());
                }

            }
        }

        return result.toString();
    }

    /**
     * Utf8URL编码
     *
     * @return
     */
    public static String GbkURLencode(String text) {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < text.length(); i++) {

            char c = text.charAt(i);
            if (c >= 0 && c <= 255) {
                result.append(c);
            } else {

                byte[] b = new byte[0];
                try {
                    b = Character.toString(c).getBytes("GB2312");
                } catch (Exception ex) {
                }

                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    result.append("%" + Integer.toHexString(k).toUpperCase());
                }

            }
        }

        return result.toString();
    }

    public static void main(String args[]) {

        try {
            // String string = "&lt;p&gt;&lt;span style=&quot;font-family: 宋体;font-size:
            // 15px&quot;&gt;&lt;span
            // style=&quot;font-family:宋体&quot;&gt;名医会诊&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;";
            // System.out.println("main.args.hexDigits " + h52wx(string));
            // String formatnum = formatnum(1, "#00");
            // System.out.println(formatnum);
            // boolean validNumber =
            // isValidNumber(String.valueOf(System.currentTimeMillis()));
            // System.out.println(validNumber);
            // StringBuffer sb = new StringBuffer().append("adsf");

            String formatnum = formatnum(0.67777, "#0.00");
            System.out.println(formatnum);

            // sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            // byte[] by = decoder.decodeBuffer("suLK1LD8");
            // String temp = new String(by);

            // String temp = GbkURLencode("台州");
            // System.out.println(StrTrimTimeWithoutDate("2012-08-16
            // 11:22:00"));
            // System.out.println(StrTrimInt("1.0"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // System.out.println(MD5Encode("60040000_rmsx_fn"));

        // System.out.println(StrTrimNumber(0l));

        // String temp =
        // "<img src=\"/image/1/194/391.jpg\"/><br/><a
        // href=\"/wap/newRMW/86264/86883/n86883d2c5444971.jsp\">美女空姐被潜规则致死</a><br/><a
        // href=\"/wap/newRMW/86264/86883/n86883d2c5410386.jsp\">瞬间男人的器官没了-上</a><br/><a
        // href=\"/wap/newRMW/86264/86883/n86883d2c5410377.jsp\">瞬间男人的器官没了-下</a><br/>";

        // getHrefOfString(temp);

        /*
         * String operatorRatecall = StringUtil.parseStrToDouble("50.05", 0.0) + "元/分钟";
         * System.out.println(operatorRatecall+"*******************"); String temp = "";
         * //temp.startsWith(prefix, toffset); // 生成代码 // String [] strarr = //
         * {"Businesscity","Businessstreet","Businesspostcode" ,"Businesscountry", //
         * "Businessstate","Businesswebpage","Businessphonenumber"
         * ,"Business2phonenumber","Homecity", //
         * "Homestreet","Homepostcode","Homecountry"
         * ,"Homestate","Companyname","Department","Jobtitle"}; // String tmpl =
         * "softcontactvo.setContact(@var);"; // printCode(strarr, tmpl); // System.out
         * //.println(decodeUnicode(
         * "&#x7CFB;&#x7EDF;&#x5F02;&#x5E38;&#xFF0C;&#x8BF7;&#x7A0D;&#x540E;&#x518D;&#x8BD5;&#x3002;"
         * )); System.out.println(decodeUnicode(
         * "&#x8bf7;&#x8f93;&#x5165;&#x624b;&#x673a;&#x53f7;&#x7801;"));
         * //gbEncoding("用户不存在，或者是您的手机号码尚未和meecall帐户绑定，请确认。"); // try // { //
         * System.out.println("转换："+new // String("&#201;&#250;&#189;&#240;&#187;&#212;"
         * .getBytes("utf-7"),"gb2312")); // // } // catch(Exception ex) // { // // } //
         * // String test = "Gsal34oe33A中国aAA"; // //
         * System.out.println(test.toUpperCase()); //
         * System.out.println(test.toLowerCase()); //
         * gbEncoding("1、编辑短信30发送到106666005002，可充值1元，总共可充值30元。"); //
         * System.out.println(getRandomUUID()); //String test = "990 13710 37-46_3 ";
         * //System.out.println(getNumberStr(test)); // test = test.replaceAll(" ", "");
         * // test = test.replaceAll("_", ""); // test = test.replaceAll("-", ""); //
         * System.out.println(test.substring(3, Math.min(14, test.length()))); //
         * gbEncoding("注： //
         * 若需要修改密码，请使用电脑访问米酷网站（www.meecall.com），登录网站后，进入【我的会员中心】进行密码修改。"); //
         * System.out.println(getRandomUUID()); String a= "尚文婕－有了爱"; String b =
         * "粱静茹－暖暖"; String c = "粱静茹－只能抱着你"; String d = "蔡依林－日不落"; String e =
         * "rain－浪漫满屋"; String f = "陈楚生－有没有人告诉你"; gbEncoding(a); gbEncoding(b);
         * gbEncoding(c); gbEncoding(d); gbEncoding(e); gbEncoding(f); String ddd=
         * "&#x0035;&#x3001;&#x65b9;&#x6cd5;&#x0032;&#x548c;&#x0033;&#x4ec5;&#x652f;&#x6301;&#x79fb;&#x52a8;&#x5f69;&#x4fe1;&#x7528;&#x6237;&#xff0c;&#x4f46;&#x662f;&#x4e0a;&#x6d77;&#x3001;&#x5c71;&#x897f;&#x3001;&#x7518;&#x8083;&#x3001;&#x6d59;&#x6c5f;&#x3001;&#x65b0;&#x7586;&#x3001;&#x5b89;&#x5fbd;&#x3001;&#x6cb3;&#x5357;&#x3001;&#x9655;&#x897f;&#x3001;&#x5b81;&#x590f;&#x7b49;&#x7701;&#x5e02;&#x6682;&#x65f6;&#x65e0;&#x6cd5;&#x4f7f;&#x7528;&#x3002;"
         * ; System.out.println(decodeUnicode(ddd)); String cccc =
         * "发送短信m8000到10669160171免费呼叫客服"; gbEncoding(cccc); int amount = (int)
         * Math.round(8.125*100); System.out.println(amount);
         */

        /*
         * try { String keyword = "张柏芝";new String("张柏芝".getBytes("gb2312"),"utf-8");
         * keyword = URLEncoder.encode(keyword,"utf-8"); System.out.print(keyword); }
         * catch(Exception ex) { }
         */

        // System.out.println(codeUnicode("<a href=\"./channel.jsp\">新闻.</a>"));
    }

    public static String[] getNamePath(String namePath) {
        int pos_wap = namePath.indexOf("人民网手机电视收费");
        int pos_client = namePath.indexOf("手机视频");
        String s = "";
        if (pos_wap >= 0) {
            s = namePath.substring(pos_wap);
        } else if (pos_client >= 0) {
            s = namePath.substring(pos_client);
        }
        if (namePath.endsWith("/")) {
            s = s.substring(0, s.length() - 1);
        }
        String[] arrNamePath = s.split("/");
        return arrNamePath;
    }

    // MD5密码加密
    public static String Md5(String password) {
        StringBuffer buf = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte b[] = md.digest();

            int i;

            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            // System.out.println("result: " + buf.toString());// 32位的加密

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    /**
     * 计算年龄
     */
    public static String getAge(Date date) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(date)) {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(date);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }

        return age + "";
    }

    public static int toInt(Object a) {
        double b = Double.parseDouble(a.toString());
        return (int) b;

    }

    /**
     * 功能描述：判断字符串绝对不为空
     *
     * @param str
     * @return 不为空时返回：true,否则返回：false
     * @author tongkp
     * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
     * @since 2016-6-22
     */
    public static boolean absNotEmpty(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
        if (str.length() < 1) {
            return false;
        }
        return true;
    }

    public static boolean isValidIP(String user_ip) {
        return !(!absNotEmpty(user_ip) || user_ip.length() < 7 || user_ip.length() > 12 || "error".equalsIgnoreCase(user_ip)
                || (user_ip.charAt(0) != 1 && user_ip.charAt(0) != 2));
    }

    /**
     * 将字符串中h5标签转换成对应微信小程序标签
     *
     * @return
     */
    public static String h52wx(Object object) {
        String str;
        if (object == null)
            str = "";
        else
            str = object.toString().trim();
        if (str == null || str.trim().toLowerCase().equals("null") || str.trim().toLowerCase().indexOf("null") >= 0)
            str = "";
        if (StringUtil.absNotEmpty(str)) {
            // 仅替换转义符 其余标签不作处理
            // str = str.replace("&lt;", "<").replace("&gt;",
            // ">").replace("&quot;",
            // "\"").replace("<strong>", "<view
            // style=\"font-weight:bold;\">").replace("</strong>",
            // "</view>").replace("<br />", "").replace("<p>",
            // "<view>").replace("</p>", "</view>").replace("<span",
            // "<view").replace("span>", "view>");
            str = str.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&nbsp;", "").replace("&amp;nbsp;", "");
            // .replaceAll("\\\\", "");
        }
        return str;
    }

    public static String urlDecode(String content) {
        return urlDecode(content, null);
    }

    public static String urlDecode(String content, String charset) {
        if (!absNotEmpty(content)) {
            return content;
        }
        if (charset == null) {
            charset = "UTF-8";
        }
        try {
            return URLDecoder.decode(content, charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 按指定格式 格式化 数字
     *
     * @param num
     * @param pattern
     * @return
     */
    public static String formatnum(double num, String pattern) {
        DecimalFormat df = new DecimalFormat(pattern);
        return df.format(num);
    }

    public static float formatNumAsFloat(double num, String pattern) {
        return StringUtil.StrTrimFloat(formatnum(num, pattern));
    }

    /**
     * 替换字符串中特殊字符 \r \n
     *
     * @param url
     * @return
     * @author xiao
     * @update [变更日期YYYY-MM-DD][更改人姓名][变更描述]
     * @since 2018年8月14日下午10:19:42
     */
    public static String replaceSpecialCharacter(String url) {
        if (CheckUtil.isEmpty(url)) {
            return url;
        }
        if (url.contains("\r")) {
            url = url.replace("\r", "");
        } else if (url.contains("\r\n")) {
            url = url.replace("\r\n", "");
        } else if (url.contains("\n")) {
            url = url.replace("\n", "");
        } else if (url.contains("\n\r")) {
            url = url.replace("\n\r", "");
        }
        return url;
    }

    // 将数组转换为字符串
    public static String arrayToStr(Object[] arr) {
        if (null == arr || arr.length == 0) {
            return null;
        }
        String str = "";
        StringBuffer sb = new StringBuffer(str);
        if (null != arr) {
            for (Object item : arr) {
                sb.append(item).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        str = sb.toString();

        return str;
    }

    public final static String wildcardCharacter = "%";

    /**
     * 包装一下模糊查询字段
     *
     * @param queryField 查询字段
     * @return 包装后的字段
     */
    public static String fuzzySearchWrapper(String queryField) {
        return wildcardCharacter + queryField + wildcardCharacter;
    }

}
